var url = require('url');
var resourceProperty = require('../common/config.js');
var logger = require('tracer').colorConsole();
var util = require('../common/util.js');
// var login = require('./login');
var fs = require('fs')
var cookie = require('cookie');
var path = require("path")

var base64Img = require('base64-img');
var log = require('hy5b/log/be');

var crypto = require('crypto');
var api = require('hy5b/axiosReq/api')
var t = require('hy5b/t/ext')
var auto = require('hy5b/auto')
var zjlibUtil = require('C:\\Users\\fengl\\workspace\\node.cpp.code\\node\\zjlib\\util');

var TMP_PATH = path.resolve(__dirname, '../../../../tmp');
var STORE_DATA_PATH = path.resolve(__dirname, '../data');

function requireProxy(module) {
  var json = { data: '' }; //show的傻逼代码
  try {
    json = require(module);
    delete require.cache[require.resolve(module)];
  } catch (e) {
    logger.warn(e)
  } finally {
    return json;
  }
}

const flag = false;

const myExports = {
  '/tenant/api/v1': function(req, res) {
    var pathname = url.parse(req.url).pathname;
    var method = req.method;

    if (method === 'POST' && pathname === '/tenant/api/v1/user/update') {
      var oReqUrl = url.parse(req.headers.referer || 'http://' + req.headers.host)
      util.formParse(req, function(err, fields, files) {
        util.setHeader(res, 'set-cookie', `skin=${fields.skin};Path=/;Domain=${oReqUrl.hostname};Max-Age=2592000`)
        util.outJson(req, res, requireProxy('../data' + pathname + '#' + method + '.json'));
      })
      return
    }

    if (flag) {
      passThrough(req, res, requireProxy('../data' + pathname + '#' + method + '.json'));
    } else {
      util.outJson(req, res, requireProxy('../data' + pathname + '#' + method + '.json'));
    }
  },
  '/tenant/styles/images': passToPng, //疯狂请求 http://localhost:7700/tenant/styles/images/cmdb-icon.png
  '/tenant/userimages': passToPng, //http://localhost:8000/tenant/userimages/default.png失败
  '/frontend/logo.png': passToPng, //http://localhost:8000/frontend/logo.png失败
  '/upload/map/map.json': function(req, res) {
    util.outJson(req, res, require('../data/_mock/map.json'))
  },
  '/upload/map/gis_tiles': function(req, res) {
    util.proxy(req, res, resourceProperty.getUrl())
  },
  '/show/upload/map/map.json': function(req, res) {
    myExports['/upload/map/map.json'](req, res);
  },
  '/show/upload/map/gis_tiles': function(req, res) {
    myExports['/upload/map/gis_tiles'](req, res);
  },
  '/upload/': passToPng,
  '/show/upload/': passToPng,
  '/file/resource/inner/mold': passToSvg,
  '/file': passToPng,
  '/show/file': passToPng,
  '/resource': passToPng,
  '/show/resource': passToPng,
  // '/api/v2/ticket/receivTicket': function(req, res) {
  //   util.proxy(req, res, 'http://10.1.200.7:7804'); //yexiang
  // },
  // '/api/v2/file/upload': function(req, res) {
  //   util.proxyMultiPartForm(req, res, 'http://10.1.200.3:7880'); //fb
  //   util.proxyMultiPartForm(req, res, 'http://10.1.240.10:7880'); //dongff
  //   util.outJson(req, res, {errCode: 200}); //yexiang
  // },
  // mock里面没有的自己造
  // '/runtimeEnvironment/engine/deploy/config': function(req, res) {
  //   util.outJson(req, res, requireProxy(path.resolve(TMP_PATH, '2018/1126/deploysaved.json')))
  // },
  // '/udapmanager/api/topo': function(req, res) {
  //   util.outJson(req, res, requireProxy(path.resolve(TMP_PATH, '2019/0110/topo.json')))
  // },
  // '/api/window/953197592fc44231b0c839f4fd490536': function(req, res) {
  //   util.outJson(req, res, requireProxy(path.resolve(TMP_PATH, '2020/0727/window.json')))
  // },

  // '/showdata/api/dataset/options/xAxis/': passToApi,
  // '/api/dataset/options/xAxis': function(req, res) {
  //   util.outJson(req, res, requireProxy(path.resolve(TMP_PATH, '2020/0331/xAxis.json')))
  // },
  // '/api/molds/resources/query?id=uyun-mold00201000000000000000001&classCode=VM&classLayerCode=Virtual%20Resource': function(req, res) {
    // util.outJson(req, res, requireProxy('../data/api/molds/resources/query1#GET.json'))
  // },
  // '/api/window/d98d3e59ce5c4bc1878bf968c2d6bff9': function(req, res) {
  //   util.outJson(req, res, requireProxy('../data/api/window/d98d3e59ce5c4bc1878bf968c2d6bff9#GET.json'))
  // },
  // '/showdata/api/dataset/options/xAxis': function(req, res) {
  //   util.formParse(req, function(err, fields, files) {
  //     var data = _.map(fields.dataSets, dataSet => {
  //       return {
  //         dataSetId: dataSet.id,
  //         fields: [],
  //         refreshTime: 20000
  //       }
  //     })

  //     util.outJson(req, res, { errCode: 200, data: data })
  //   })
  // },
  '/showdata/api/datasource/names/chart': function(req, res) {
    if (resourceProperty.USE_MOCK) {
      util.outJson(req, res, requireProxy('../data/_mock/dataSourceList.json'))
    } else {
      myExports['/api/'](req, res);
    }
  },
  '/showdata/api/dataset/options/names/bdb24f053f864cca9300d4b1c608271c': function(req, res) {
    if (resourceProperty.USE_MOCK) {
      util.outJson(req, res, requireProxy('../data/_mock/dataSetList.json'))
    } else {
      myExports['/api/'](req, res);
    }
  },
  '/showdata/api/dataset/bdb24f053f864cca9300d4b1c608271c': function(req, res) {
    if (resourceProperty.USE_MOCK) {
      util.outJson(req, res, requireProxy('../data/_mock/dataSet.json'))
    } else {
      myExports['/api/'](req, res);
    }
  },
  '/showdata/api/dataset/options/xAxis/bdb24f053f864cca9300d4b1c608271c': function(req, res) {
    if (resourceProperty.USE_MOCK) {
      util.outJson(req, res, requireProxy('../data/_mock/dataSetFieldList.json'))
    } else {
      myExports['/api/'](req, res);
    }
  },
  '/showdata/api/dataset/querydata/bdb24f053f864cca9300d4b1c608271c': function(req, res) {
    if (resourceProperty.USE_MOCK) {
      util.outJson(req, res, requireProxy('../data/_mock/data.json'))
    } else {
      myExports['/api/'](req, res);
    }
  },
  // '/api/molds/classes': function(req, res) {
  //   util.outJson(req, res, requireProxy('../data/_mock/moldClasses.json'))
  // },
  // '/api/molds/cmdb/classes': function(req, res) {
  //   util.outJson(req, res, requireProxy('../data/_mock/cmdbMoldClasses.json'))
  // },
  '/udapmanager': function(req, res) {
    passThrough2(req, res, resourceProperty.getRootUrl())
  },
  '/udap': function(req, res) {
    passThrough2(req, res, resourceProperty.getRootUrl())
  },
  '/dashboard': function(req, res) {
    passThrough2(req, res, resourceProperty.getRootUrl())
  },
  // '/showdata/api/dataset/test': function(req, res) {
  //   util.outJson(req, res, { errCode: 200 })
  // },
  // '/showdata/api/dataset/field': function(req, res) {
  //   util.outJson(req, res, { errCode: 200, data: { field: [{fieldName:'id',dataType:''}, {fieldName:'value',dataType:''}] } })
  // },
  '/showdata/api': function(req, res) {
    passThrough2(req, res, resourceProperty.getRootUrl())
  },
  '/api/verify': function(req, res, next) {
    if (0) {
      res.statusCode = 401;
      res.end()
    } else {
      passToApi(req, res)
    }
  },
  '/api/v1/assets': function(req, res) {
    if (1) {
      passThrough2(req, res, "https://testnets-api.opensea.io");
    } else {
      const oReqUrl = url.parse(req.url);
      const owner = oReqUrl.query.split("&")[0].split("=");
      util.outJson(req, res, requireProxy(`../data/_mock/mynft-${owner[1]}.json`))
    }
  },
  '/api/root-proxy': function(req, res) {
    var ourl = url.parse(req.url);
    var pathname = ourl.pathname;
    var urlPath = ourl.path.replace(/^\/api\/root-proxy/, '');
    var method = req.method;
    passThrough(req, res, requireProxy('../data' + pathname + '#' + method + '.json'), urlPath, resourceProperty.getRootUrl())
  },
  '/event/': function(req, res) {
    var ourl = url.parse(req.url);
    var pathname = ourl.pathname;
    var urlPath = ourl.path.replace(/^\/api/, '');
    // if (/^\/show/.test(pathname)) {
    //   pathname = pathname.replace(/^\/show/, '');
    //   urlPath = urlPath.replace(/^\/show/, '');
    // }
    var method = req.method;
    try {
      // console.log(pathname, urlPath)
      passThrough(req, res, requireProxy('../data' + pathname + '#' + method + '.json'), urlPath);
      // util.proxyMultiPartForm(req, res, resourceProperty.getUrl())
    } catch (e) {
      logger.error(e);
      util.outJson(req, res, { errCode: 404, message: e.message });
    }
  },
  '/api/': function(req, res) {
    var ourl = url.parse(req.url);
    var pathname = ourl.pathname;
    var urlPath = ourl.path.replace(/^\/api/, '');
    // if (/^\/show/.test(pathname)) {
    //   pathname = pathname.replace(/^\/show/, '');
    //   urlPath = urlPath.replace(/^\/show/, '');
    // }
    var method = req.method;
    try {
      // console.log(111, pathname, urlPath)
      passThrough(req, res, requireProxy('../data' + pathname + '#' + method + '.json'), urlPath);
      // util.proxyMultiPartForm(req, res, resourceProperty.getUrl())
    } catch (e) {
      logger.error(111, e);
      util.outJson(req, res, { errCode: 404, message: e.message });
    }
  },
  '/verify': passToApi,
  '/notify': passToApi,
  '/show/api': passToApi,
  '/show': function(req, res, next) {
    next();
  },
  '/hm': function(req, res) {
    var ourl = url.parse(req.url);
    var pathname = ourl.pathname;
    var urlPath = ourl.path;
    // var urlPath = ourl.path.replace(/^\/api/, '');
    // if (/^\/show/.test(pathname)) {
    //   pathname = pathname.replace(/^\/show/, '');
    //   urlPath = urlPath.replace(/^\/show/, '');
    // }
    var method = req.method;
    try {
      // console.log(pathname, urlPath)
      passThrough(req, res, requireProxy('../data' + pathname + '#' + method + '.json'), urlPath, resourceProperty.getRootUrl() + '/approval');
      // util.proxyMultiPartForm(req, res, resourceProperty.getUrl())
    } catch (e) {
      logger.error(e);
      util.outJson(req, res, { errCode: 404, message: e.message });
    }
  },
  // '/set-cookie': function(req, res) {
  //   var setCookies = []
  //   var cookies = require('../common/cookies')
  //   cookies.forEach(obj => {
  //     setCookies.push(cookie.serialize(obj.name, obj.value, {
  //       path: '/',
  //       domain: 'localhost',
  //       expires: new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000)
  //     }));
  //   })
  //   util.setHeader(res, 'Set-Cookie', setCookies);
  //   res.end(0)
  // }
  '//home/zy_home.jsp': function(req, res) {
    var queryString = url.parse(req.url).query;
    const _get = t.parseQueryString(queryString);
    const cookies = t.parseCookie(req.headers.cookie);
    if (!cookies || !cookies.JSESSIONID || _get.relogin === '1') {
      zjlibUtil.getCookies().then(res1 => {
        const setCookies = res1.headers['set-cookie'];
        const cookies = t.parseSetCookie(setCookies);
        cookies.clientlanguage = "zh_CN";
        zjlibUtil.login(cookies).then(res2 => {
          util.setHeader(res, 'Content-Type', 'text/html; charset=utf-8');
          util.setHeader(res, 'Set-Cookie', setCookies);
          util.setHeader(res, 'Location', "http://" + req.headers.host + req.url.replace('&relogin=1', ''));
          res.statusCode = 302;
          res.end();
        });
      })
    } else {
      util.proxy(req, res, 'http://zjisa.zjlib.cn/', function(res, body) {
        let bodyString = body.toString().replace(/http:\/\/zjisa\.zjlib\.cn\/sso\/auth\.jsp/g, "http://" + req.headers.host + '/sso/auth.jsp');
        bodyString = bodyString.replace(/http:\/\/zjisa\.zjlib\.cn:80\/\/elecClick\.jsp/g, "http://" + req.headers.host + '//elecClick.jsp');
        bodyString = bodyString.replace("</body>", '<a href="javascript:(function(){location.href=location.href+&quot;&relogin=1&quot;})();" style=\"position:fixed;top:100px;left:0;padding:6px 20px;background-color:#fff;\"">重新登录</a></body>');
        res.end(bodyString);
        return true;
      });
    }
  },
  '/sso/auth.jsp': function(req, res) {
    const cookies = t.parseCookie(req.headers.cookie);
    if (cookies.infcn_server && cookies.clientId) {
      // console.log('----------111----------')
      // console.log(cookies)
      zjlibUtil.open("http://zjisa.zjlib.cn/sso/auth.jsp?returnUrl=http://zjgxgc.vip.qikan.cn/&libCode=zjlib", cookies).then(res1 => {
        // console.log('---------------11111111------------')
        // console.log(res1.headers)
        util.setHeader(res, 'Location', "http://" + req.headers.host + "/rwt/124/http/QJWGP8DHMMYHM4LRF3ZXT45BNZYGG5C/text/text.aspx");
        res.statusCode = 302;
        res.end();
      });
    } else {
      // console.log('-----------222---------')
      zjlibUtil.open("http://zjisa.zjlib.cn/sso/auth.jsp?returnUrl=http://zjgxgc.vip.qikan.cn/&libCode=zjlib", cookies).then(res1 => {
        const setCookies2 = res1.headers['set-cookie'];
        const cookies2 = t.parseSetCookie(setCookies2);
        const allCookies = Object.assign({}, cookies2, cookies);
        console.log(setCookies2, allCookies)
        zjlibUtil.open("http://zjisa.zjlib.cn/sso/auth.jsp?returnUrl=http://zjgxgc.vip.qikan.cn/&libCode=zjlib", allCookies).then(res2 => {
          // console.log('---------------22222222------------')
          // console.log(res2.headers)
          util.setHeader(res, 'Content-Type', 'text/html; charset=utf-8');
          util.setHeader(res, 'Set-Cookie', setCookies2);
          util.setHeader(res, 'Location', "http://" + req.headers.host + "/rwt/124/http/QJWGP8DHMMYHM4LRF3ZXT45BNZYGG5C/text/text.aspx")
          res.statusCode = 302;
          res.end();
        });
      });
    }
  },
  '//elecClick.jsp': function(req, res) {
    var queryString = url.parse(req.url).query;
    const cookies = t.parseCookie(req.headers.cookie);
    zjlibUtil.register('http://zjisa.zjlib.cn//elecClick.jsp?' + queryString,cookies).then(res1 => {
      res.end();
    })
  },
}

module.exports = myExports

//////////
//从这里保留 //
//////////

module.exports['/api/example/upload'] = function(req, res) {
  //outJson就直接返回
  util.formParse(req, function(err, fields, files) {
    if (err) {
      logger.error(err);
      util.outJson(req, res, { errCode: 201, message: err.message });
      return;
    }
    var icon = fields.window.icon;
    if (/^data:image\/png;base64,/.test(icon)) {
      base64Img.img(icon, './attachment', 'icon-' + Date.now(), function(err, filepath) {
        if (err)
          log.error(err);
        else
          log.info('icon has been stored to ' + filepath);
      })
    } else {
      log.error(icon + ' is not a effective base64 image data!');
    }
    for (var param in fields) {
      logger.log(param + ': ' + fields[param]);
    }
    for (var param in files) {
      logger.log(param + ': ' + files[param].name, files[param].size, files[param].path);
    }
  })
  util.outJson(req, res, { year: 1994 });
}

module.exports['/api/example/outJson'] = function(req, res) {
  // res.statusCode = 500
  //outJson就直接返回
  util.outJson(req, res, {
    errCode: 200,
    message: '',
    // filter: filter,
    // options: options,
    data: [{
      id: 0,
      name: 'Kate',
      email: 'kate@gamil.com'
    }, {
      id: 1,
      name: 'Lily',
      email: 'lily@hotmail.com'
    }]
  });
}

module.exports['/api/example/passThrough'] = function(req, res) {
  //使用passThrough可以灵活配置，只要在passThrough改一个if语句就可以全部透传了
  passThrough(req, res, { errCode: 200 });
}

//返回指定结果或代理到服务
function passThrough(req, res, o, resetReqUrl, target) {
  if (resourceProperty.USE_MOCK) {
    util.paramLog(req)
    setTimeout(function() {
      util.outJson(req, res, o);
    }, 1);
    return;
  }
  util.proxy(req, res, target || resourceProperty.getUrl(), function(res, body) {
    // if (req.url.indexOf('/api/getUserAuth') !== -1) {
    //   setTimeout(function() {
    //     res.end(body);
    //   }, 2000);
    //   return true
    // }
  }, resetReqUrl);
}
//返回缓存结果或代理到服务
function passThrough2(req, res, path, resetReqUrl) {
  if (resourceProperty.USE_MOCK) {
    var ourl = url.parse(resetReqUrl || req.url);
    var pathname = ourl.pathname;
    var method = req.method;
    util.outJson(req, res, requireProxy('../data' + pathname + '#' + method + '.json'))
  } else {
    util.proxy(req, res, path);
  }
}

function passToPng(req, res) {
  util.setHeader(res, 'Content-Type', 'image/png');
  // res.end('');
  var fileSteam = fs.createReadStream('./hotdocs/1px.png');
  fileSteam.pipe(res); 
}

function passToSvg(req, res) {
  util.setHeader(res, 'Content-Type', 'image/svg+xml;charset=UTF-8');
  var fileSteam = fs.createReadStream('./hotdocs/1.svg');
  fileSteam.pipe(res); 
}

function passToApi(req, res) {
  myExports['/api/'](req, res);
}

//////////
//到这里结束 //
//////////
